import {Passkey} from 'react-native-passkey';
import {startAuthenticationUsername} from '../api/anonymous-actor-api';
import {useAccountProvider} from './useAccountProvider';
import {useCallback} from 'react';
import {PasskeyAuthFailed} from '../types/errors';

export function usePasskeyAuth() {
  const {userInfo} = useAccountProvider();
  const passkeyAuth = useCallback(async () => {
    if (userInfo == undefined) {
      throw new Error('Invalid user.');
    }

    const response = await startAuthenticationUsername(userInfo.userName);
    const authOptions = JSON.parse(response).publicKey;
    return Passkey.get({
      ...authOptions,
    })
      .then(asseResp => {
        console.log('usePasskeyAuth [asseResp]', asseResp);
        return JSON.stringify(asseResp);
      })
      .catch(error => {
        console.log('startAuthenticationUsername passkey', error);
        throw new PasskeyAuthFailed();
      });
  }, [userInfo]);

  return {
    passkeyAuth,
  };
}
